<template>
  <div class="register-form login-register">
    <section class="mlogin-user">
      <section class="mlogin-name">
        <section class="mlogin-left tel">手机号码</section>
        <section class="mlogin-right">
          <input
            type="text"
            name="mobile"
            v-model="formDataRegister.mobile"
            placeholder="请输入您的手机号码"
            value
          />
        </section>
      </section>
      <section class="mlogin-name">
        <section class="mlogin-left password">密码</section>
        <section class="mlogin-right">
          <input
            type="password"
            name="password"
            v-model="formDataRegister.password"
            placeholder="设置密码"
            value
          />
        </section>
      </section>
      <section class="mlogin-name" v-if="this.check_apply_mobile==1">
        <section class="mlogin-left verify">验证码</section>
        <section class="mlogin-right">
          <input
            type="text"
            placeholder="请输入右图验证码"
            name="verify"
            class="setpwd-text"
            v-model="formDataRegister.verify"
          />
        </section>
        <img :src="verifyImg" class="code-img" @click="refreshVerify" />
      </section>
      <section class="mlogin-name" v-if="this.check_apply_mobile==1">
        <section class="mlogin-left msg-verify">短信验证码</section>
        <section class="mlogin-right">
          <input
            type="text"
            placeholder="请输入短信验证码"
            name="code"
            class="setpwd-text"
            v-model="formDataRegister.msgVerify"
          />
        </section>
        <a class="msg-verify-btn" href="javascript:;" @click="refreshmsgVerify">{{msgVerifyTxt}}</a>
      </section>
      <section class="mlogin-name">
        <section class="mlogin-left referrer">推荐人</section>
        <section class="mlogin-right">
          <input
            type="text"
            class="referrer-id"
            name="r_pid"
            v-model="formDataRegister.r_pid"
            placeholder="填写推荐人ID或手机号（必填）"
            value
            v-if="is_need_recommend==1"
          />
          <input
            type="text"
            class="referrer-id"
            name="r_pid"
            v-model="formDataRegister.r_pid"
            placeholder="填写推荐人ID或手机号（非必填）"
            value
            v-else
          />
        </section>
      </section>
    </section>
    <section class="mlogin-but" @click="register">
      <van-button round hairline href="javascript:;" class="btn red-gra-btn">确定提交</van-button>
    </section>
  </div>
</template>

<script>
import Vue from 'vue'

import {
  getRegInfo,
  getVerify,
  postMsgVerify,
  postReg,
  postIsMobileExist
} from '@/api/loginRegister/index'
import { validLength, validateMobile } from '@/utils/validate'
import Store from '@/utils/store'
import { getRegister } from '@/api/dz/dzApi'
export default Vue.extend({
  data() {
    return {
      verifyImg: '', // 图形验证码
      check_apply_mobile: 0, // 验证手机号
      is_app: false,
      is_need_recommend: 0, // 推荐人是否必填
      isMobileExist: 0,
      msgVerifyTxt: '获取验证码',
      formDataRegister: {
        mobile: '',
        password: '',
        verify: '',
        msgVerify: '',
        r_pid: ''
      },
      sid: '',
      testShop: [6, 3739, 3829, 3842, 3737], // 测试使用的店铺id
      isTestShop: false
    }
  },
  methods: {
    // 获取后台开关设置
    regInfo() {
      if (this.$route.query.sid) {
        this.sid = this.$route.query.sid
      } else {
        this.sid = Store.fetchLocal('sid') ? Store.fetchLocal('sid') : undefined
      }
      this.testShop.findIndex((item) => {
        if (this.sid == item) {
          this.isTestShop = true
          return false
        }
      })
      getRegInfo().then(res => {
        if (res.status === 1) {
          const data = res.data
          this.check_apply_mobile = data.check_apply_mobile
          this.is_app = data.is_app
          this.is_need_recommend = data.is_need_recommend
        }
      })
    },
    // 刷新验证码
    refreshVerify() {
      getVerify().then(res => {
        const src =
          'data:image/jpg;base64,' +
          btoa(
            new Uint8Array(res).reduce(
              (data, byte) => data + String.fromCharCode(byte),
              ''
            )
          )
        this.verifyImg = src
      })
    },
    // 验证手机号码是否已注册
    validateIsMobileExist() {
      postIsMobileExist({ mobile: this.formDataRegister.mobile }).then(res => {
        if (res.status === 1) {
          if (res.data == 1) {
            this.isMobileExist = 1
          }
        } else {
          this.$Error(res.msg)
        }
      })
    },
    // 获取验证码倒计时
    setTimeoutVerify() {
      let count = 60
      this.msgVerifyTxt = count + '秒后重新获取'
      const timer = setInterval(() => {
        this.msgVerifyTxt = count + '秒后重新获取'
        if (count <= 0) {
          this.msgVerifyTxt = '获取验证码'
          clearInterval(timer)
        }
        count--
      }, 1000)
    },
    // 获取短信验证码
    refreshmsgVerify() {
      if (this.msgVerifyTxt == '获取验证码') {
        const mobile = this.formDataRegister.mobile
        const password = this.formDataRegister.password
        const verify = this.formDataRegister.verify
        if (validateMobile(mobile)) {
          if (validLength(password, 5)) {
            if (validLength(verify)) {
              this.validateIsMobileExist()
              if (this.isMobileExist == 1) {
                this.$Error('您所填写的号码已注册')
                this.isMobileExist == 0 // 提示已注册后恢复该值为0
                return false
              } else {
                const data = { mobile: mobile, code: verify }
                postMsgVerify(data).then(res => {
                  if (res.status === 1) {
                    this.setTimeoutVerify()
                    // console.log(res)
                  } else {
                    this.$Error(res.msg)
                  }
                })
              }
            } else {
              this.$Error('请输入验证码')
              return false
            }
          } else {
            this.$Error('密码长度不能少于6位')
            return false
          }
        } else {
          this.$Error('请输入正确的手机号码')
          return false
        }
      }
    },
    // 注册提交
    register() {
      const mobile = this.formDataRegister.mobile
      const password = this.formDataRegister.password
      const verify = this.formDataRegister.verify
      const msgVerify = this.formDataRegister.msgVerify
      const r_pid = this.formDataRegister.r_pid
      // 如果是自动化测试店铺，只验证手机号长度
      if (this.isTestShop) {
        if (!validLength(mobile)) {
          this.$Error('请输入正确的手机号码')
          return false
        }
      } else {
        if (!validateMobile(mobile)) {
          this.$Error('请输入正确的手机号码')
          return false
        }
      }

      if (!validLength(password, 5)) {
        this.$Error('密码长度不能少于6位')
        return false
      }
      if (this.check_apply_mobile == 1) {
        if (!validLength(verify)) {
          this.$Error('请输入验证码')
          return false
        }
        if (!validLength(msgVerify)) {
          this.$Error('请输入短信验证码')
          return false
        }
      }
      if (Number(this.is_need_recommend) == 1) {
        if (!validLength(r_pid)) {
          this.$Error('请输入推荐人ID或手机号码')
          return false
        }
      }
      // 如果后台开启了验证手机号码,code为短信验证码
      const data = {}
      if (this.check_apply_mobile == 1) {
        data.mobile = mobile
        data.password = password
        data.code = msgVerify
        data.r_pid = r_pid
      } else {
        data.mobile = mobile
        data.password = password
        // data.code = verify
        data.r_pid = r_pid
      }
      postReg(data).then(res => {
        if (res.status === 1) {
          if (res.data.user_id) {
            Store.saveLocal('uid', res.data.user_id)
          }
          window.location.href = res.data.url
        } else {
          this.$Error(res.msg)
          this.refreshVerify()
        }
      })
    }
  },
  created() {
    this.refreshVerify()
    this.regInfo()
  }
})
</script>

<style lang="scss">
@import "src/styles/loginRegister";
.msg-verify-btn {
  font-size: 26px;
}
.mlogin-name .invite {
  background-image: url('https://img.wifenxiao.com/h5-wfx/images/loginRegister/invite_code.png');
  background-size: 100% auto;
  background-position: center;
  background-repeat: no-repeat;
}
</style>